package javase.ch02.homeWork.Test1;

/**
 * 创建对象方式有哪些？总结并写代码
 * 3.通过clone方法创建对象
 *      调用clone方法创建对象
 *      对象必须实现Cloneable接口，否则会抛出CloneNotSupportedException异常
 *      一般基于已有对象复制出一个新对象
 */
public class CloneDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        Book book1 = new Book("Java编程",9.9);
        Book book2 = book1.clone();
        System.out.println(book2);
    }
}
class Book implements Cloneable{
    private String name;
    private double price;
    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    // 重写clone方法
    @Override
    protected Book clone() throws CloneNotSupportedException {
        return (Book) super.clone();
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
